from flask import render_template, current_app, session, request, jsonify

from info.models import User,News,Category
from info import constants
from utils.response_code import RET
from . import index_blu

@index_blu.route('/news_list')
def news_list():
    # cid = request.args.get('cid','1')
    # page = request.args.get('page','1')
    # per_page = request.args.get("per_page","10")
    # # 校验
    # try:
    #     cid = int(cid)
    #     page = int(page)
    #     per_page = int(per_page)
    # except Exception as e :
    #     current_app.logger.error(e)
    #     # return jsonify
    #     return jsonify(errno=RET.DATAERR, errmsg="传入不是数字")
    #
    # filters = []
    # if cid != 1:
    #     filters.append(News.category_id==cid)
    # try:
    #     paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    # except Exception as e :
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DATAERR, errmsg="数据库操作错误")
    #
    # new_list = []
    # current_page = paginate.page
    # pages = paginate.pages
    # items = paginate.items
    # for item in items:
    #     new_list.append(item.to_dict())
    # data = {
    #     "current": current_page,
    #     "pages": pages,
    #     "new_list":new_list
    # }
    # return jsonify(errno=RET.OK, errmsg="成功",data=data)
    # cid = request.args.get("cid", "1")
    # page = request.args.get("page", "1")
    # per_page = request.args.get("per_page", "10")
    #
    # # 2. 校验参数
    # try:
    #     page = int(page)
    #     cid = int(cid)
    #     per_page = int(per_page)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.PARAMERR, errmsg="参数")
    #
    # filters = []
    # if cid != 1:  # 查询的不是最新的数据
    #     # 需要添加条件
    #     filters.append(News.category_id == cid)
    #
    # # if cid != 1:
    # #     paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page, per_page, False)
    # # else:
    # #     paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page, per_page, False)
    #
    # # 3. 查询数据
    # try:
    #     paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    #
    # # 取到当前页的数据
    # news_model_list = paginate.items  # 模型对象列表
    # total_page = paginate.pages
    # current_page = paginate.page
    #
    # # 将模型对象列表转成字典列表
    # news_dict_li = []
    # for news in news_model_list:
    #     news_dict_li.append(news.to_basic_dict())
    #
    # data = {
    #     "total_page": total_page,
    #     "current_page": current_page,
    #     "news_dict_li": news_dict_li
    # }
    #
    # return jsonify(errno=RET.OK, errmsg="OK", data=data)

    #TODO 从这里开始
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    news_dict_li = []


    if cid != 1:
        paginate = News.query.filter(News.category_id==cid).order_by(News.create_time.desc()).paginate(page,per_page,False)
    else:
        paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page,per_page,False)
    current_page = paginate.page
    total_pages = paginate.pages
    items = paginate.items
    for item in items :
        news_dict_li.append(item.to_dict())

    data = {
        'current_page':current_page,
        'total_page':total_pages,
        'news_dict_li': news_dict_li
    }
    return jsonify(errno=RET.OK, errmsg="成功",data=data)

@index_blu.route('/')
def index():
    # 显示用户是否登陆的逻辑
    # user_id = session.get('user_id',None)
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e :
    #         current_app.logger.error(e)
    #
    #
    # news_list = []
    # # 右侧的新闻逻辑
    # try:
    #     news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    # except Exception as e :
    #     current_app.logger.error(e)
    # news_dict = []
    # for news in news_list:
    #     news_dict.append(news.to_dict())
    #
    # cate_list = []
    # categories = Category.query.all()
    # for category in categories:
    #     cate_list.append(category.to_dict())
    #
    #
    # data = {
    #     'user': user.to_dict() if user else None,
    #     'news_dict': news_dict,
    #     'cate_list': cate_list
    # }
    #
    # return render_template('news/index.html',data=data)
    #
    # 第一步要验证登陆
    # 第二步查询数据库
    user_id = session.get('user_id',None)
    try:
        user = User.query.filter(User.id==user_id).first()
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")


    news_list = []
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")
    for new in news:
        news_list.append(new.to_dict())
    cate_list = []
    categoies = Category.query.all()
    for category in categoies:
        cate_list.append(category.to_dict())

    data = {
        "user":user.to_dict() if user else None,
        'news_dict':news_list,
        'cate_list':cate_list
    }

    return render_template('news/index.html',data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
